package com.software.car.service;

import com.github.pagehelper.PageHelper;
import com.software.car.api.ExampleService;
import com.software.car.api.ModelService;
import com.software.car.api.ProjectSercvice;
import com.software.car.common.enums.ResultEnum;
import com.software.car.common.exception.MyException;
import com.software.car.common.utils.CommonPage;
import com.software.car.common.utils.SnowflakeIdGenerator;
import com.software.car.entity.dto.ExampleDto;
import com.software.car.entity.dto.ExampleValueDto;
import com.software.car.entity.dto.ProjectDto;
import com.software.car.entity.vo.*;
import com.software.car.mapper.ProjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author 魔法はまだ解けない
 * @Date 2021/3/20
 */
@Service
public class ProjectSercviceImpl implements ProjectSercvice {
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    ModelService modelService;

    @Autowired
    ExampleService exampleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addProject(ProjectDto projectDto) {
        String id = SnowflakeIdGenerator.getId();
        projectDto.setId(id);
        projectDto.setCreateTime(new Date());
        int i = projectMapper.addProjcet(projectDto);
        if(i==0){
            throw new MyException(ResultEnum.INSERT_FAILD);
        }
        String modelId = projectDto.getModelId();
        ModelVo model = modelService.getModel(modelId, 1);
        if(model==null){
            throw new MyException(ResultEnum.MODEL_NOT_EXIT);
        }

        //构造一个空1型实例，插入null值
        ExampleDto exampleDto = new ExampleDto();
        List<ExampleValueDto> exampleValuelist = new ArrayList<>();
        model.getOptions().forEach(e->{
            ExampleValueDto value = new ExampleValueDto();
            value.setOptionId(e.getId());
            value.setValue("");
            exampleValuelist.add(value);
        });
        exampleDto.setType(1);
        exampleDto.setProjectId(projectDto.getId());
        exampleDto.setExampleValuelist(exampleValuelist);

        exampleService.addExample(exampleDto);
        modelService.updateModel(projectDto.getModelId(),2,projectDto.getCreateUser());
        return id;
    }

    @Override
    public int updateProject(ProjectDto projectDto) {
        int i = projectMapper.updateProjcet(projectDto);
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProject(String projectId) {
        //删除项目
        int i = projectMapper.deleteProject(projectId);
        //删除实例
        exampleService.deleteExampleAll(projectId);
        return i;
    }

    @Override
    public CommonPage getSimpleProject(Integer page, Integer pageSize, Integer state,String createUser) {
        if (page==null||pageSize==null){
            page=1;
            pageSize=10;
        }
        PageHelper.startPage(page,pageSize);
        List<ProjectEasyVo> simpleProject = projectMapper.getSimpleProject(state,createUser);
        CommonPage wrap = CommonPage.wrap(simpleProject);
        return wrap;
    }

    @Override
    public ProjectDetailVo getProject(String projectId) {
        ProjectDetailVo project = projectMapper.getProject(projectId);
        if (project==null){
            return null;
        }

        /**
         * 获取使用的模板
         */
        ModelVo model = modelService.getModel(project.getModelId(), 1);
        project.setModelVo(model);
        /**
         *  获取项目的，1型实例
         * 没有则设置成null
         */
        List<String> exampleList = exampleService.getExampleList(projectId, 1);
        if(exampleList.isEmpty()){
            project.setFormOptions(null);
        }else {
            //获取模id、模板选项表、实例值表
            String exampleId1 = exampleList.get(0);
            List<ModelOptionVo> options = model.getOptions();
            List<ExampleValueVo> exampleValueDtos = exampleService.getExampleValueDtos(exampleId1);

            /**
             * 构造一个hashMap对象
             * key：模板id
             * value：实例值
             * 遍历模板，循环每个模板id，对应找到一个实例值，如果没有，就赋值null
             */
            HashMap<String, String> form1 = new HashMap<>();
            form1.put("id",exampleId1);
            options.forEach(e->{
                form1.put(e.getId(),null);
                for (int i = 0; i < exampleValueDtos.size(); i++) {
                    if(e.getId().equals(exampleValueDtos.get(i).getOptionId())){
                        form1.put(e.getId(),exampleValueDtos.get(i).getValue());
                        break;
                    }
                }
            });
            project.setFormOptions(form1);
        }
        /**
         * 获取表格，构造返回体
         */
        List<ModelTableOptionVo> tableModel = model.getTableOptions();
        //构造返回数据
        project.setTableOptions(new ArrayList<>());
        List<HashMap<String,String>> tableOptions2 = project.getTableOptions();
        ArrayList<List<ExampleValueVo>> tableList = new ArrayList<>();
        project.setTableList(tableList);

        /**
         *  获取项目的，2型实例
         * 没有则设置成null
         */
        List<String> exampleList2 = exampleService.getExampleList(projectId, 2);
        if(exampleList2.isEmpty()){
            project.setTableOptions(null);
        }else {
            //遍历实例
            exampleList2.forEach(s1 -> {
                //获取实例值列表
                List<ExampleValueVo> exampleValueDtos2 = exampleService.getExampleValueDtos(s1);
                /**
                 * 构造一个hashMap对象
                 * key：模板id
                 * value：实例值
                 * 遍历模板，循环每个模板id，对应找到一个实例值，如果没有，就赋值null
                 */
                HashMap<String, String> tableObject = new HashMap<>();
                tableObject.put("id",s1);
                tableModel.forEach(e->{
                    tableObject.put(e.getId(),null);
                    for (int i = 0; i < exampleValueDtos2.size(); i++) {
                        if(e.getId().equals(exampleValueDtos2.get(i).getOptionId())){
                            tableObject.put(e.getId(),exampleValueDtos2.get(i).getValue());
                            break;
                        }
                    }
                });
                tableOptions2.add(tableObject);
                tableList.add(exampleValueDtos2);
            });
        }
        return project;
    }


}
